//
//  HCalendarViewController.swift
//  Drop
//
//  Created by hushaohua on 2018/5/5.
//  Copyright © 2018年 init. All rights reserved.
//

import UIKit

private let reuseIdentifier = "calendar"
private let resultReuseIdentifier = "result"
private let resultHeaderReuseIdentifier = "resultHeader"

enum HCalendarPickType {
    case unit //单日/周/月
    case discrete //离散值
    case continuous //开始结束
}

class HCalendarViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
    
    var intervalType:HTimeIntervalType = .day;
    var pickedType:HCalendarPickType = .unit;
    var calendarTitle:String = "";
    var pickedDates:[DateComponents] = [DateComponents]();
    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.backgroundColor = UIColor.white;
        
        self.configNavigation();
        self.getDefaultCurrentSuperDate();
        self.view.addSubview(self.dateNavigationView);//next/previous month
        self.setupNavigation();
        if (self.intervalType != .month){
            self.view.addSubview(self.weekHeaderView);//monday,tuesday,....,sunday
        }
        self.view.addSubview(self.collectionView);//days
        self.setupCollectionView();
        self.getDaysCount();
        self.getItemCount();
        self.getCurrentInfos();
        self.reloadDays();
    }
    
    func configNavigation() {
        if self.calendarTitle.count == 0 {
            self.navigationItem.title = "选择时间";
        }else{
            self.navigationItem.title = self.calendarTitle;
        }
        var done = UIBarButtonItem(title: "Done", style: .done, target: self, action: #selector(doneAction));
        done = UIBarButtonItem(customView: self.doneButton);
        self.doneButton.isEnabled = false;
        self.navigationItem.rightBarButtonItem = done;
    }
    
    lazy var doneButton:UIButton = {
        var button:UIButton = UIButton(frame: CGRect(x:0,y:0,width:64,height:44));
        button.setTitle("Done", for: .normal);
        button.setTitleColor(UIColor.lightGray, for: .disabled);
        button.setTitleColor(UIColor.h_blue(), for: .normal);
        button.contentHorizontalAlignment = .right;
        button.titleLabel?.font = UIFont.systemFont(ofSize: 18);
        button.addTarget(self, action: #selector(doneAction), for: .touchUpInside);
        return button;
    }();
    
    var doneClosure:((HTimeIntervalType, HCalendarPickType, [DateComponents]) -> Void)?;
    @objc func doneAction() {
        if (self.doneClosure != nil){
            self.doneClosure!(self.intervalType, self.pickedType, self.pickedDates);
        }
        self.navigationController?.popViewController(animated: true);
    }
    
    func setupCollectionView(){
        self.collectionView.register(HCalendarDayCell.self, forCellWithReuseIdentifier: reuseIdentifier);
        self.collectionView.register(HCalendarResultCell.self, forCellWithReuseIdentifier: resultReuseIdentifier);
        self.collectionView.register(HCalendarResultHeaderView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: resultHeaderReuseIdentifier)
        if (self.intervalType == .day && self.pickedType == .unit){
            self.collectionView.allowsMultipleSelection = false;
        }else{
            self.collectionView.allowsMultipleSelection = true;
        }
        self.reloadDays();
    }
    
    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil);
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    var currentSuperDate:Date = Date(){
        didSet{
            self.dateNavigationView.previousButton.isEnabled = self.isPreviousAvailable();
            self.dateNavigationView.nextButton.isEnabled = self.isNextAvailable();
            self.getDaysCount();
            self.getItemCount();
            self.getCurrentInfos();
        }
    }
    
    func getDefaultCurrentSuperDate() {
        if (self.intervalType == .month){
            let components = Calendar.current.dateComponents([.year], from: Date());
            self.currentSuperDate = Calendar.current.date(from: components)!;
        }else{
            let components = Calendar.current.dateComponents([.year, .month], from: Date());
            self.currentSuperDate = Calendar.current.date(from: components)!;
        }
    }
    
    var previousDay:Int = 30;//上月最后一天
    func getDaysCount() {
        if (self.intervalType != .month){
            let calendar = Calendar.current;
            let range = calendar.range(of: .day, in: .month, for: self.currentSuperDate);
            var component = DateComponents();
            component.day = -1;
            let preDayDate = calendar.date(byAdding: component, to: self.currentSuperDate);
            component = calendar.dateComponents([.day], from: preDayDate!);
            self.previousDay = component.day!;
            self.daysCount = range!.count;
        }else{
        }
    }
    
    var daysCount:Int = 0;
    func getItemCount() {
        if (self.intervalType != .month){
            let weekday = Calendar.current.component(.weekday, from: self.currentSuperDate);
            self.collectionViewLayout.firstWeekday = weekday;
            self.collectionViewLayout.itemsCount = self.daysCount;
        }else{
            self.collectionViewLayout.itemsCount = 12;
        }
        self.collectionViewLayout.getFullItemCount();
    }
    func reloadDays(_ animated:Bool = false){
        self.collectionViewLayout.getCellAttributes();
        self.collectionViewLayout.getSectionAttributes();
        self.collectionViewLayout.getResultCellAttributes();
        if (animated){
            self.collectionView.reloadSections([0]);
        }else{
            self.collectionView.reloadData();
        }
    }
    
    var showToday:Bool = true;
    var todayIndex:Int = 0;
    func getCurrentInfos(){
        self.showToday = false;
        self.todayIndex = -1;
        let todayComponents = Calendar.current.dateComponents([.year, .month, .day], from: Date());
        if (self.intervalType == .month){
            let diff = Calendar.current.dateComponents([.year], from: Date(), to: self.currentSuperDate);
            if (diff.year! == 0){
                self.showToday = true;
                self.todayIndex = todayComponents.month! - 1;
            }
            return;
        }
        let diff = Calendar.current.dateComponents([.month], from: Date(), to: self.currentSuperDate);
        if (diff.month! == 0){
            self.showToday = true;
            if (self.intervalType == .day){
                self.todayIndex = todayComponents.day! - 1;
            }else{
                self.todayIndex = self.collectionViewLayout.firstDayOfCurrentMonth + todayComponents.day! - 1;
            }
        }else if (self.intervalType == .week){
            if diff.month! == -1 {
                if (self.collectionViewLayout.firstDayOfCurrentMonth >= self.previousDay - todayComponents.day!){
                    self.showToday = true;
                    self.todayIndex = self.collectionViewLayout.firstDayOfCurrentMonth - (self.previousDay - todayComponents.day! + 1);
                }
            }else if diff.month! == 1 {
                if (self.collectionViewLayout.fullWeeksItemCount - (self.collectionViewLayout.firstDayOfCurrentMonth + self.daysCount) >= todayComponents.day!){
                    self.showToday = true;
                    self.todayIndex = self.collectionViewLayout.firstDayOfCurrentMonth + self.daysCount + todayComponents.day! - 1;
                }
            }
        }
    }
    
    func setupNavigation(){
        self.reloadNavigation();
        self.dateNavigationView.previousButton.addTarget(self, action: #selector(gotoPreviousMonth), for: .touchUpInside);
        self.dateNavigationView.nextButton.addTarget(self, action: #selector(gotoNextMonth), for: .touchUpInside);
    }
    
    func reloadNavigation() {
        if (self.intervalType == .month){
            let components = Calendar.current.dateComponents([.year], from: self.currentSuperDate);
            self.dateNavigationView.yearButton.setTitle("\(components.year!)", for: .normal);
        }else{
            let components = Calendar.current.dateComponents([.year, .month], from: self.currentSuperDate);
            self.dateNavigationView.monthButton.setTitle("\(components.month!)月", for: .normal);
            self.dateNavigationView.yearButton.setTitle("\(components.year!)", for: .normal);
        }
    }
    
    func isPreviousAvailable() -> Bool{
        let date = DDateManager.sharedManager().initDate?.firstMonthDay(after: 0);
        if (self.intervalType == .month){
            let diff = Calendar.current.dateComponents([.year], from: self.currentSuperDate, to: date!);
            return diff.year! < 0;
        }else{
            let diff = Calendar.current.dateComponents([.month], from: self.currentSuperDate, to: date!);
            return diff.month! < 0;
        }
    }
    @objc func gotoPreviousMonth(){
        
        if (self.intervalType == .month){
            self.currentSuperDate = Calendar.current.date(byAdding: .year, value: -1, to: self.currentSuperDate, wrappingComponents: false)!;
        }else{
            self.currentSuperDate = Calendar.current.date(byAdding: .month, value: -1, to: self.currentSuperDate, wrappingComponents: false)!;
        }
        self.reloadNavigation();
        self.reloadDays();
    }
    
    func isNextAvailable() -> Bool{
        if (self.intervalType == .month){
            let diff = Calendar.current.dateComponents([.year], from: Date(), to: self.currentSuperDate);
            return diff.year! < 0;
        }else{
            let diff = Calendar.current.dateComponents([.month], from: Date(), to: self.currentSuperDate);
            return diff.month! < 0;
        }
    }
    @objc func gotoNextMonth(){
        if (self.intervalType == .month){
            self.currentSuperDate = Calendar.current.date(byAdding: .year, value: 1, to: self.currentSuperDate, wrappingComponents: false)!;
        }else{
            self.currentSuperDate = Calendar.current.date(byAdding: .month, value: 1, to: self.currentSuperDate, wrappingComponents: false)!;
        }
        self.reloadNavigation();
        self.reloadDays();
    }
    
    lazy var pickedView:HCalendarPickedView = {
        var view:HCalendarPickedView = HCalendarPickedView(frame: CGRect(x:0,y:0,width:self.view.bounds.size.width, height:30));
        return view;
    }();
    
    lazy var weekHeaderView:HCalendarWeeksView = {
        var view:HCalendarWeeksView = HCalendarWeeksView(frame: CGRect(x:0,y:110,width:self.view.bounds.width,height:30));
        view.backgroundColor = UIColor(white: 0.95, alpha: 1);
        return view;
    }();
    
    lazy var dateNavigationView:HCalendarNavigationView = {
        var view:HCalendarNavigationView = HCalendarNavigationView(frame: CGRect(x:0, y:64, width:self.view.bounds.size.width, height:44), year:(self.intervalType == .month));
        view.backgroundColor = UIColor(white: 0.98, alpha: 1);
        return view;
    }();
    
    func collectionSizePadding() -> (width:CGFloat, padding:CGFloat){
        let width:CGFloat = (self.view.bounds.size.width - 10 - 6) / 7;
//        width = CGFloat(floorf(Float(width)));
//        let margin:CGFloat = (UIScreen.main.bounds.size.width - width * 7) / 2;
        return (width, 5);
    }
    
    lazy var collectionViewLayout:HCalendarCollectionViewLayout = {
        let layout:HCalendarCollectionViewLayout = HCalendarCollectionViewLayout(interval: self.intervalType);
        if (self.intervalType == .month){
            layout.contentInset = UIEdgeInsetsMake(10, 10, 80, 10);
            layout.itemSpace = CGPoint(x: 10, y: 10);
            layout.itemSize = CGSize(width: (self.view.bounds.size.width - 40) / 3, height: 80);
        }else{
            let sizePadding = self.collectionSizePadding();
            layout.itemSpace = CGPoint(x: 1, y: 1);
            layout.itemSize = CGSize(width: sizePadding.width, height: sizePadding.width);
            layout.contentInset = UIEdgeInsetsMake(3, sizePadding.padding, 80, sizePadding.padding);
        }
        if self.pickedType == .continuous{
            layout.resultSize = CGSize(width: self.view.bounds.size.width - 20, height: 40);
            layout.resultsCountPerRow = 1;
        }else{
            layout.resultSize = CGSize(width: (self.view.bounds.size.width - 30) / 2, height: 40);
            layout.resultsCountPerRow = 2;
        }
        return layout;
    }();
    
    lazy var collectionView:UICollectionView = {
        let offsetY:CGFloat = (self.intervalType == .month ? 110 : 140);
        var view:UICollectionView = UICollectionView(frame: CGRect(x:0,y:offsetY,width:self.view.bounds.width,height:self.view.bounds.height - offsetY), collectionViewLayout: self.collectionViewLayout);
        view.backgroundColor = UIColor(white: 0.98, alpha: 1);
        view.dataSource = self;
        view.delegate = self;
        view.allowsMultipleSelection = false;
        return view;
    }();

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: UICollectionViewDataSource
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 2;
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if (section == 0){
            return self.collectionViewLayout.fullItemCount();
        }else{
            return self.collectionViewLayout.resultsCount;
        }
    }
    
    func resultCollectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> HCalendarResultCell {
        let cell:HCalendarResultCell = collectionView.dequeueReusableCell(withReuseIdentifier: resultReuseIdentifier, for: indexPath) as! HCalendarResultCell;
        
        switch self.pickedType {
        case .unit:
            let first = self.pickedDates.first!;
            let last = self.pickedDates.last!;
            switch self.intervalType{
            case .day:
                cell.textLabel.text = "\(first.month!)-\(first.day!)";
            case .month:
                cell.textLabel.text = "\(first.year!)-\(first.month!)";
            case .week:
                cell.textLabel.text = "\(first.month!)-\(first.day!) 至 \(last.month!)-\(last.day!)";
            }
        case .continuous:
            let first = self.pickedDates.first!;
            let last = self.pickedDates.last!;
            var current = first;
            var prefix = "";
            
            if (indexPath.item > 0){
                current = last;
            }
            if self.pickedDates.count > 1 {
                prefix = indexPath.item == 0 ? "开始: " : "结束: ";
            }
            
            switch self.intervalType{
            case .day:
                cell.textLabel.text = "\(prefix)\(current.month!)-\(current.day!)";
            case .month:
                cell.textLabel.text = "\(prefix)\(current.year!)-\(current.month!)";
            case .week:
                if self.pickedDates.count > 7 {
                    prefix = indexPath.item == 0 ? "开始周: " : "结束周: ";
                }else{
                    prefix = "";
                }
                var weekFirst = first;
                var weekLast = first;
                if indexPath.item > 0 {
                    weekFirst = self.pickedDates[self.pickedDates.count - 7];
                    weekLast = last;
                }else{
                    weekFirst = first;
                    weekLast = self.pickedDates[6];
                }
                cell.textLabel.text = "\(prefix)\(weekFirst.month!)-\(weekFirst.day!) 至 \(weekLast.month!)-\(weekLast.day!)";
            }
        case .discrete:
            let comp = self.pickedDates[indexPath.item];
            switch self.intervalType{
            case .day:
                cell.textLabel.text = "\(comp.month!)-\(comp.day!)";
            case .month:
                cell.textLabel.text = "\(comp.year!)-\(comp.month!)";
            case .week:
                var weekFirst = self.pickedDates[indexPath.item * 7];
                var weekLast = self.pickedDates[indexPath.item * 7 + 6];
                cell.textLabel.text = "\(weekFirst.month!)-\(weekFirst.day!) 至 \(weekLast.month!)-\(weekLast.day!)";
            }
        }
        return cell;
    }
    
    func calendarCollectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> HCalendarDayCell {
        let cell:HCalendarDayCell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! HCalendarDayCell;
        switch self.intervalType {
        case .month:
            cell.textLabel.font = UIFont.italicSystemFont(ofSize: 36);
            cell.textLabel.text = "\(indexPath.item + 1)月";
            cell.textLabel.textColor = UIColor.gray;
        case .week:
            cell.textLabel.font = UIFont.systemFont(ofSize: 20, weight: .thin);
            if (indexPath.item < self.collectionViewLayout.firstDayOfCurrentMonth){
                cell.textLabel.text = "\(self.previousDay - (self.collectionViewLayout.firstDayOfCurrentMonth - indexPath.item - 1))";
                cell.textLabel.textColor = UIColor.lightGray;
            }else if (indexPath.item >= self.collectionViewLayout.firstDayOfCurrentMonth + self.daysCount){
                cell.textLabel.text = "\(indexPath.item - self.collectionViewLayout.firstDayOfCurrentMonth - self.daysCount + 1)";
                cell.textLabel.textColor = UIColor.lightGray;
            }else{
                cell.textLabel.text = "\(indexPath.item - self.collectionViewLayout.firstDayOfCurrentMonth + 1)";
                cell.textLabel.textColor = UIColor.darkGray;
            }
        case .day:
            cell.textLabel.text = "\(indexPath.item + 1)";
            cell.textLabel.textColor = UIColor.darkGray;
        }
        if (self.showToday && self.todayIndex == indexPath.item){
            cell.textLabel.textColor = UIColor.h_blue();
        }
        cell.mark = self.isIndexPathSelected(indexPath);
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        if (indexPath.section == 0){
            return self.calendarCollectionView(collectionView, cellForItemAt: indexPath);
        }else{
            return self.resultCollectionView(collectionView, cellForItemAt: indexPath);
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        let view = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: resultHeaderReuseIdentifier, for: indexPath);
        return view;
    }
    
    func isIndexPathSelected(_ indexPath:IndexPath) -> Bool{
        if (self.intervalType == .month){
            let date = Calendar.current.date(byAdding: .month, value: indexPath.item, to: self.currentSuperDate);
            var comp = Calendar.current.dateComponents([.year, .month], from: date!);
            for dateComponent in self.pickedDates {
                if (comp.year == dateComponent.year
                    && comp.month == dateComponent.month){
                    return true;
                }
            }
        }else{
            let date = Calendar.current.date(byAdding: .day, value: (indexPath.item - (self.intervalType == .day ? 0 : self.collectionViewLayout.firstDayOfCurrentMonth)), to: self.currentSuperDate);
            var comp = Calendar.current.dateComponents([.year, .month, .day], from: date!);
            for dateComponent in self.pickedDates {
                if (comp.year == dateComponent.year
                    && comp.month == dateComponent.month
                    && comp.day == dateComponent.day){
                    return true;
                }
            }
        }
        
        return false;
    }
    
    func dayDateComponentAtIndexPath(_ indexPath:IndexPath) -> DateComponents{
        let date = Calendar.current.date(byAdding: .day, value: indexPath.item, to: self.currentSuperDate);
        let comp = Calendar.current.dateComponents([.year, .month, .day], from: date!);
        return comp;
    }
    
    func monthDateComponentAtIndexPath(_ indexPath:IndexPath) -> DateComponents{
        var dateComponent = Calendar.current.dateComponents([.year], from: self.currentSuperDate);
        dateComponent.month = indexPath.item + 1;
        return dateComponent;
    }
    
    func weekDateComponentAtIndexPath(_ indexPath:IndexPath) -> [DateComponents]{
        let row = indexPath.item / 7;
        var comps = [DateComponents]();
        for index in 0...6 {
            let indexPath = IndexPath(item: index + row * 7, section: 0);
            let date = Calendar.current.date(byAdding: .day, value: (indexPath.item - self.collectionViewLayout.firstDayOfCurrentMonth), to: self.currentSuperDate);
            let comp = Calendar.current.dateComponents([.year, .month, .day], from: date!);
            comps.append(comp);
        }
        return comps;
    }

    func selectDayIndexPath(_ indexPath:IndexPath){
        let dateComponent = self.dayDateComponentAtIndexPath(indexPath);
        self.pickedDates.append(dateComponent);
        self.collectionView.reloadData();
    }
    
    func selectWeekIndexPath(_ indexPath:IndexPath){
        let dateComponents = self.weekDateComponentAtIndexPath(indexPath);
        self.pickedDates += dateComponents;
        self.collectionView.reloadData();
    }
    
    func selectMonthIndexPath(_ indexPath:IndexPath){
        let dateComponent = self.monthDateComponentAtIndexPath(indexPath);
        self.pickedDates.append(dateComponent);
        self.collectionView.reloadData();
    }
    
    func deselectDayIndexPath(_ indexPath:IndexPath){
        let comp = self.dayDateComponentAtIndexPath(indexPath);
        self.deselectDateComponent(comp);
        self.collectionView.reloadData();
    }
    
    func deselectWeekIndexPath(_ indexPath:IndexPath){
        let dateComponents = self.weekDateComponentAtIndexPath(indexPath);
        for comp in dateComponents {
            self.deselectDateComponent(comp);
        }
        self.collectionView.reloadData();
    }
    
    func deselectMonthIndexPath(_ indexPath:IndexPath){
        let comp = self.monthDateComponentAtIndexPath(indexPath);
        self.deselectDateComponent(comp);
        self.collectionView.reloadData();
    }
    
    func deselectDateComponent(_ comp:DateComponents){
        for index in 0..<self.pickedDates.count {
            let dateComponent = self.pickedDates[index];
            if (comp.year == dateComponent.year
                && comp.month == dateComponent.month
                && comp.day == dateComponent.day){
                self.pickedDates.remove(at: index);
                return;
            }
        }
    }
    
    func dateComponentAtIndexPath(_ indexPath:IndexPath) -> [DateComponents]{
        switch self.intervalType {
        case .day:
            return [self.dayDateComponentAtIndexPath(indexPath)];
        case .week:
            return self.weekDateComponentAtIndexPath(indexPath);
        case .month:
            return [self.monthDateComponentAtIndexPath(indexPath)];
        }
    }
    
    func getResultItems() {
        var resultCount = 0;
        switch self.intervalType {
        case .day, .month:
            resultCount = self.pickedDates.count;
        case .week:
            resultCount = self.pickedDates.count / 7;
        }
        if (self.pickedType == .continuous && resultCount > 0){
            resultCount = resultCount > 1 ? 2 : 1;
        }
        self.collectionViewLayout.resultsCount = resultCount;
        self.collectionViewLayout.getResultCellAttributes();
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if (indexPath.section != 0){
            return;
        }
        let cell:HCalendarDayCell = collectionView.cellForItem(at: indexPath) as! HCalendarDayCell;
        switch self.pickedType {
        case .unit:
            self.handleUnitSelect(indexPath: indexPath, cell: cell);
        case .discrete:
            self.handleDiscretSelect(indexPath: indexPath, cell: cell);
        case .continuous:
            self.handleContinuousSelect(indexPath: indexPath, cell: cell);
        }
        self.getResultItems();
    }
    
    func handleContinuousSelect(indexPath:IndexPath, cell:HCalendarDayCell){
        let comp = self.dateComponentAtIndexPath(indexPath);
        if (self.pickedDates.count == 0){
            self.pickedDates += comp;
            self.collectionView.reloadData();
        }else if ((self.pickedDates.count == 1) || (self.intervalType == .week && self.pickedDates.count == 7)){
            let existFirst = self.pickedDates.first!;
            let existLast = self.pickedDates.last!;
            switch existFirst.compareWith(comp.first!) {
            case .orderedDescending:
                //选择了一个前面的时间
                self.doneButton.isEnabled = true;
                self.pickedDates.removeAll();
                self.pickedDates += (self.intervalType == .month ? DateComponents.monthDateComponentsArray(from: comp.first!, to: existLast) : DateComponents.dayDateComponentsArray(from: comp.first!, to: existLast));
            case .orderedAscending:
                //选择了一个后面的时间
                self.doneButton.isEnabled = true;
                self.pickedDates.removeAll();
                self.pickedDates += (self.intervalType == .month ? DateComponents.monthDateComponentsArray(from: existFirst, to: comp.last!) : DateComponents.dayDateComponentsArray(from: existFirst, to: comp.last!));
            case .orderedSame:
                self.pickedDates.removeAll();
                break;
            }
            self.collectionView.reloadData();
        }else{
            let firstComp = self.pickedDates.first!;
            let lastComp = self.pickedDates.last!;
            let compareFirst = comp.first!.compareWith(firstComp);
            let compareLast = comp.last!.compareWith(lastComp);
            if (compareFirst == .orderedSame){
                self.doneButton.isEnabled = false;
                self.pickedDates.removeFirst(self.pickedDates.count - (self.intervalType == .week ? 7 : 1));
                self.collectionView.reloadData();
            }else if (compareLast == .orderedSame){
                self.doneButton.isEnabled = false;
                self.pickedDates.removeLast(self.pickedDates.count - (self.intervalType == .week ? 7 : 1));
                self.collectionView.reloadData();
            }else if (compareFirst == .orderedAscending){//更早的开始日期
                let preDates = (self.intervalType == .month ? DateComponents.monthDateComponentsArray(from: comp.first!, to: firstComp, ignoreFrom: false, ignoreTo: true) : DateComponents.dayDateComponentsArray(from: comp.first!, to: firstComp, ignoreFrom: false, ignoreTo: true));
                self.pickedDates.insert(contentsOf: preDates, at: 0);
                self.collectionView.reloadData();
            }else if (compareLast == .orderedDescending){//更晚的结束日期
                let nextDates = (self.intervalType == .month ? DateComponents.monthDateComponentsArray(from: lastComp, to: comp.last!, ignoreFrom: true) : DateComponents.dayDateComponentsArray(from: lastComp, to: comp.last!, ignoreFrom: true));
                self.pickedDates.append(contentsOf: nextDates);
                self.collectionView.reloadData();
            }else{//选择更晚的开始日期   /   更早的结束日期
                self.showSetBeginOrEndMenuAt(indexPath);
                self.indexPathForSetBeginOrEnd = indexPath;
            }
        }
    }
    var indexPathForSetBeginOrEnd:IndexPath?;
    func showSetBeginOrEndMenuAt(_ indexPath:IndexPath){
        let begin = UIMenuItem(title: "Begin", action: #selector(setBeginMenuAction));
        let end = UIMenuItem(title: "End", action: #selector(setEndMenuAction));
        let menuController = UIMenuController.shared;
        menuController.menuItems = [begin, end];
        let attributes = self.collectionViewLayout.layoutAttributesForItem(at: indexPath);
        menuController.setTargetRect(attributes!.frame, in: self.collectionView);
        menuController.setMenuVisible(true, animated: true);
    }
    
    
    override var canBecomeFirstResponder: Bool{
        return true;
    }
    
    @objc func setBeginMenuAction(){
        self.doneButton.isEnabled = true;
        let comp = self.dateComponentAtIndexPath(self.indexPathForSetBeginOrEnd!);
        self.indexPathForSetBeginOrEnd = nil;
        let lastComp = self.pickedDates.last!;
        let nextDates = DateComponents.dayDateComponentsArray(from: comp.first!, to: lastComp);
        self.pickedDates.removeAll();
        self.pickedDates += nextDates;
        self.collectionView.reloadData();
    }
    
    @objc func setEndMenuAction() {
        self.doneButton.isEnabled = true;
        let comp = self.dateComponentAtIndexPath(self.indexPathForSetBeginOrEnd!);
        self.indexPathForSetBeginOrEnd = nil;
        let firstComp = self.pickedDates.first!;
        let dates = DateComponents.dayDateComponentsArray(from: firstComp, to: comp.last!);
        self.pickedDates.removeAll();
        self.pickedDates += dates;
        self.collectionView.reloadData();
    }
    
    func handleUnitSelect(indexPath:IndexPath, cell:HCalendarDayCell){
        if (cell.mark){
            return;
        }
        self.doneButton.isEnabled = true;
        self.pickedDates.removeAll();
        switch self.intervalType {
        case .day:
            self.selectDayIndexPath(indexPath);
        case .week:
            self.selectWeekIndexPath(indexPath);
        case .month:
            self.selectMonthIndexPath(indexPath);
        }
    }
    func handleDiscretSelect(indexPath:IndexPath, cell:HCalendarDayCell){
        switch self.intervalType {
        case .day:
            !cell.mark ? self.selectDayIndexPath(indexPath) : self.deselectDayIndexPath(indexPath);
            self.doneButton.isEnabled = self.pickedDates.count > 0;
        case .week:
            !cell.mark ? self.selectWeekIndexPath(indexPath) : self.deselectWeekIndexPath(indexPath);
            self.doneButton.isEnabled = self.pickedDates.count >= 7;
        case .month:
            !cell.mark ? self.selectMonthIndexPath(indexPath) : self.deselectMonthIndexPath(indexPath);
            self.doneButton.isEnabled = self.pickedDates.count > 0;
        }
    }
}
